﻿using OneDark.Git;
using OneDark.Sqlite;
using OneDark.Update;
using OneDark.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;

namespace OneDark
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly ObservableCollection<GitProperty> gitProperties = new ObservableCollection<GitProperty>();
        private readonly ConfigRdr configRdr = new ConfigRdr();

        private readonly GitUpdate gitUpdate = new GitUpdate();

        public MainWindow()
        {
            InitializeComponent();
            dg_GitProjects.ItemsSource = gitProperties;

            ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dg_GitProjects.ItemsSource);
            if (cvTasks != null && cvTasks.CanSort == true)
            {
                cvTasks.SortDescriptions.Clear();
                cvTasks.SortDescriptions.Add(new SortDescription("Project", ListSortDirection.Ascending));
                cvTasks.SortDescriptions.Add(new SortDescription("Url", ListSortDirection.Descending));
                cvTasks.SortDescriptions.Add(new SortDescription("LastCommit", ListSortDirection.Descending));
            }
            if (cvTasks != null && cvTasks.CanGroup == true)
            {
                //cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("Folder"));
            }
            configRdr.Load();
            DbMgr.Setup();
        }

        private void BtnGetFolder_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls"
            };
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbShowPath.Text = openFileDialog.FileName;
            }
        }

        /// <summary>
        /// 查找所有Git项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnGo_Click(object sender, RoutedEventArgs e)
        {
            string path = this.tbShowPath.Text.Trim();
            gitProperties.Clear();
            List<GitProperty> gits = await gitUpdate.GetGitPathsAsync(".git");
            gits.ForEach(p => gitProperties.Add(p));
            await Task.Run(() =>
             {
                 gitUpdate.LoadReposAsync();
                 gitUpdate.CheckRespRepeat(gitProperties.ToList());
             });
        }

        /// <summary>
        /// 分析，主要是获取扩展信息，包括提交次数、最后提交时间、本地文件变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_Analysis_Click(object sender, RoutedEventArgs e)
        {
            List<Task> lstTask = new List<Task>();
            var progress = new Progress<float>();
            progress.ProgressChanged += (psender, args) =>
            {
                pg_Loading.Value = (double)args * 100;
            };
            await gitUpdate.BatchUpdateExtParas(progress);
            await Task.Run(() => gitUpdate.CheckRespRepeat(gitProperties.ToList()));
            gitProperties.OrderBy(i => i.LastCommit).ThenBy(i => i.Url).ThenBy(i => i.Project);
            //await Task.Run(() => gitUpdate.Save());
        }

        /// <summary>
        /// 开始批量更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_StartBatchUpdate_Click(object sender, RoutedEventArgs e)
        {
            int iThreads = Convert.ToInt32(tbx_UpdateThreads.Text);
            btn_CancleBatchUpdate.IsEnabled = true;
            btn_StartBatchUpdate.IsEnabled = false;
            Progress<float> progress = new Progress<float>();
            progress.ProgressChanged += (psender, args) =>
            {
                pg_Update.Value = (double)args * 100;
            };
            await Task.Run(() => gitUpdate.RunUpdate(iThreads, progress));
            btn_CancleBatchUpdate.IsEnabled = false;
            btn_StartBatchUpdate.IsEnabled = true;
            System.Windows.MessageBox.Show("Finished");
        }

        /// <summary>
        /// 取消批量更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CancleBatchUpdate_Click(object sender, RoutedEventArgs e)
        {
            gitUpdate.CancleUpdate();
            btn_CancleBatchUpdate.IsEnabled = false;
            btn_StartBatchUpdate.IsEnabled = true;
        }

        /// <summary>
        /// 导出Git仓库列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Export_Click(object sender, RoutedEventArgs e)
        {
            DataTable dt = DatatableUtil<GitProperty>.ToDataTable<GitProperty>(gitProperties.ToList());
            string path = Environment.CurrentDirectory + "\\Source_" + DateTime.Now.ToString("yyyMMddHHmm") + ".xls";
            NPOIHelper.Export(dt, "sheet", path);
        }

        /// <summary>
        /// 项目/工程Uri链接打开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hpl_ProjectUrl_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink link = sender as Hyperlink;
            // 激活的是当前默认的浏览器
            string Uri = link.NavigateUri.IsFile ? link.NavigateUri.ToString() : link.NavigateUri.AbsoluteUri;
            Process.Start(new ProcessStartInfo(Uri));
        }

        /// <summary>
        /// 按文件夹分组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbx_GroupByFolders_Checked(object sender, RoutedEventArgs e)
        {
            bool bChecked = false;
            cbx_GroupByFolders.IsChecked.GetValueOrDefault(bChecked);
            ICollectionView cvTasks = CollectionViewSource.GetDefaultView(dg_GitProjects.ItemsSource);
            cvTasks.GroupDescriptions.Clear();
            if (cvTasks != null && cvTasks.CanGroup == true && bChecked)
            {
                cvTasks.GroupDescriptions.Add(new PropertyGroupDescription("Folder"));
            }
        }

        /// <summary>
        /// GridView中的按键点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_GitOper_Click(object sender, RoutedEventArgs e)
        {
            GitProperty gitProperty = dg_GitProjects.SelectedItem as GitProperty;
            OneDark.Git.Repository oRep = new OneDark.Git.Repository()
            {
                Name = gitProperty.Project,
                Path = gitProperty.Path
            };
            oRep.Open();
            List<Commit> commits = oRep.Commits("-n 1");
        }

        private void GitBatchUpdate_Closing(object sender, CancelEventArgs e)
        {
            DbMgr.TearDown();

            //gitUpdate.Save();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (dg_GitProjects.SelectedItem as GitProperty != null)
            {
                (dg_GitProjects.SelectedItem as GitProperty).IsFavorite = true;
            }
        }
    }
}